package cn.easier.activity.console.controller;

import cn.easier.activity.console.configration.ActivityConsoleConfiguration;
import cn.easier.activity.console.entity.PeriodicalMessageParams;
import cn.easier.activity.console.repository.ActivityPeriodicalRepository;
import cn.easier.activity.console.service.ActivityPeriodicalService;
import cn.easier.activity.console.utils.FileUtil;
import cn.easier.activity.web.entity.PeriodicalMessage;
import cn.easier.club.base.dto.ResultInfo;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

@Controller
@RequestMapping("/periodicalMessage")
public class ActivityPeriodicalController extends BaseController{

    private static Logger logger = LoggerFactory.getLogger(ActivityPeriodicalController.class);

    private final ActivityConsoleConfiguration activityConsoleConfiguration;
    private final ActivityPeriodicalRepository activityPeriodicalRepository;
    private final ActivityPeriodicalService activityPeriodicalService;

    public ActivityPeriodicalController(ActivityConsoleConfiguration activityConsoleConfiguration, ActivityPeriodicalService activityPeriodicalService, ActivityPeriodicalRepository activityPeriodicalRepository) {
        this.activityConsoleConfiguration = activityConsoleConfiguration;
        this.activityPeriodicalService = activityPeriodicalService;
        this.activityPeriodicalRepository = activityPeriodicalRepository;
    }

    /**
     * 查看所有期刊
     * @return
     */
    @RequestMapping(value = "/getMessage", method = RequestMethod.GET)
    @ResponseBody
    public ResultInfo getMessage(@RequestParam(value = "activityId", required = false) Integer activityId,
                                 @RequestParam(value = "pageNum", required = true) int pageNum,
                                 @RequestParam(value = "pageSize", required = true) int pageSize) {
        List<Object> result = activityPeriodicalService.getMessage(activityId, pageNum, pageSize);
        Object o = result.get(result.size() - 1);
        result.remove(result.size() - 1);
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), String.valueOf(o), result);
    }

    /**
     * 回显接口
     * @return
     */
    @RequestMapping(value = "/getMessageById/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResultInfo getMessageById(@PathVariable Integer id) {
        return activityPeriodicalService.getMessageById(id);
    }

    /**
     * 所有期刊名称
     * @return
     */
    @RequestMapping(value = "/getPeriodicalTitle", method = RequestMethod.GET)
    @ResponseBody
    public ResultInfo getActivityName() {
        return activityPeriodicalService.getPeriodicalTitle();
    }

    /**
     * 添加期刊相关信息
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/addPeriodicalMessage")
    public ResultInfo addPeriodicalMessage(@RequestBody PeriodicalMessageParams params) {
        return activityPeriodicalService.addPeriodicalMessage(params);
    }

    /**
     * 编辑期刊相关信息
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/updatePeriodicalMessage")
    public ResultInfo updatePeriodicalMessage(@RequestBody PeriodicalMessageParams params) {
        return activityPeriodicalService.updatePeriodicalMessage(params);
    }

    /**
     * 发布活动对象
     * @param id 活动对象Id
     * @return
     */
    @PostMapping("/id/{id}")
    @ResponseBody
    public ResultInfo release(@PathVariable Integer id) {
        return activityPeriodicalService.release(id);
    }

    /**
     * 删除期刊
     * @return
     */
    @ResponseBody
    @DeleteMapping(value = "/delPeriodical/{id}")
    public ResultInfo delMessage(@PathVariable Integer id) {
        return activityPeriodicalService.delMessage(id);
    }

    /**
     * 活动上下架(上线或暂停)
     * @param id   活动对象Id
     * @param flag 是否上架
     * @return
     */
    @PostMapping("/id/{id}/run-or-pause")
    @ResponseBody
    public ResultInfo runOrPause(@PathVariable Integer id, Boolean flag) {
        if (flag == null) {
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "操作有误，请核实信息。", null);
        }
        PeriodicalMessage periodicalMessage = new PeriodicalMessage();
        Boolean returnFlag = false;
        String user = getPrincipal().getUsername();
        String authoritiesStr = getPrincipal().getAuthoritiesStr();
        try {
            if (authoritiesStr.equals("ROLE_USER_SUPERADMIN") || authoritiesStr.equals("ROLE_USER_ADMIN")) {
                periodicalMessage = activityPeriodicalRepository.findOne(id);
            } else {
                periodicalMessage = activityPeriodicalRepository.findByCreateByAndStatusIsNotAndId(user, 2, id);
            }
            if (periodicalMessage == null) {
                logger.info("指定活动上下架失败，没有找到活动, id: =>{}", id);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "活动上下架失败，没有找到活动", null);
            }
            if (authoritiesStr.equals("ROLE_USER_SUPERADMIN") || authoritiesStr.equals("ROLE_USER_ADMIN")) {
                returnFlag = activityPeriodicalService.runOrPauseOrSuperUser(flag, id);
            } else {
                returnFlag = activityPeriodicalService.runOrPause(flag, id, user);
            }
            logger.info("指定活动" + (flag ? "上" : "下") + "架，执行完成：=>{}, id: =>{}", returnFlag ? "成功" : "失败", id);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "活动" + (flag ? "上" : "下") + "架" + (returnFlag ? "成功" : "失败"), null);
        } catch (Exception e) {
            logger.info("活动上下架异常,id：=>{}", id);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "活动上下架异常", null);
        }
    }

    /**
     * 上传图片
     */
    @PostMapping("/uploadImage")
    @ResponseBody
    public ResultInfo uploadImage(@RequestParam(value = "id", required = false) String id, @RequestParam(value = "file", required = false) MultipartFile file) {
        logger.info("上传图片,file: =>{},Id:=>{}",file,id);
        PeriodicalMessage periodicalMessage = new PeriodicalMessage();
        String user = getPrincipal().getUsername();
        String prefix = "pc_";
        String relativePath = activityConsoleConfiguration.activityAdvancedSettingPcImagePath;
        try {
            //图片上传
            if (file != null && (!Strings.isNullOrEmpty(file.getOriginalFilename()))) {
                String fileName = file.getOriginalFilename();
                //验证图片文件格式
                boolean imageFormatFlag = FileUtil.imageFormatVerification(fileName);
                if (!imageFormatFlag) {
                    return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "请选择格式为*.jpg、*.gif、*.bmp、*.png、*.jpeg 的图片", fileName);
                }
                if (id != null && !id.equals("undefined")) {
                    periodicalMessage = activityPeriodicalRepository.findOne(Integer.valueOf(id));
                    if (periodicalMessage == null) {
                        logger.error("上传期刊对应的图片异常，找不到指定的期刊活动对象。user: =>{},activityInfoId:=>{}", user, id);
                        return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "找不到指定的期刊活动对象", null);
                    }
                    periodicalMessage.setBackgroundImage(uploadFile(file, relativePath, "background_image_" + prefix));
                    activityPeriodicalRepository.save(periodicalMessage);
                    return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", periodicalMessage);
                } else {
                    String path = (uploadFile(file, relativePath, "background_image_" + prefix));
                    return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", path);
                }
            }
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "上传图片失败", null);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("创建活动高级设置失败，activityInfoId：=>{}", id,e);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "上传图片失败", null);
        }
    }

    private String uploadFile(MultipartFile imageFile, String relativePath, String fileNamePrefix) {
        //根路径
        String realPath = activityConsoleConfiguration.realPath;
        //绝对路径
        String absolutePath = (realPath + relativePath).replace("/", File.separator);
        String imageFileName = FileUtil.doFile(imageFile, absolutePath, fileNamePrefix);
        //静态资源映射 + 文件地址 + 上传文件名称
        return relativePath + imageFileName;
    }
}